from django.shortcuts import render
from django.http import JsonResponse
import json
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from django.utils import timezone
from django.db import models

# Create your views here.

@csrf_exempt
def track_event(request):
    """
    用户行为跟踪API
    接收前端发送的用户行为数据并记录
    """
    print(f"接收到行为跟踪请求: {request.path}, 方法: {request.method}")
    
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': '仅支持POST请求'}, status=405)
    
    try:
        # 解析JSON数据
        print(f"尝试解析数据: {request.body}")
        data = json.loads(request.body)
        event_type = data.get('event_type')
        event_data = data.get('event_data', {})
        
        # 获取用户IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip_address = x_forwarded_for.split(',')[0].strip()
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        
        # 获取用户代理
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        
        # 获取会话ID
        session_id = request.session.session_key
        if not session_id:
            request.session.create()
            session_id = request.session.session_key
        
        # 记录用户ID（如果已登录）
        user_id = request.user.user_id if request.user.is_authenticated else None
        
        # 获取URL和引用页
        page_url = data.get('page_url', request.META.get('HTTP_REFERER', ''))
        referrer = data.get('referrer')
        
        # 设置对象类型和ID
        object_type = event_data.get('object_type', None)
        object_id = event_data.get('product_id', None)  # 兼容前端传参格式
        
        # 获取查询参数
        query = data.get('query', None)
        
        # 将数据写入数据库
        with connection.cursor() as cursor:
            cursor.execute("""
                INSERT INTO tb_user_behavior
                (user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address, create_time)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """, [
                user_id,
                session_id,
                event_type,
                object_type,
                object_id,
                page_url,
                query,
                user_agent,
                ip_address,
                timezone.now()
            ])
            # 显式提交事务
            connection.commit()
        
        print(f"SQL执行成功，影响行数: {cursor.rowcount}")
        print(f"SQL执行完成，当前时间: {timezone.now()}, 会话ID: {session_id}, 事件类型: {event_type}")
        
        return JsonResponse({
            'status': 'success',
            'message': '事件已记录'
        })
    except Exception as e:
        # 记录错误，方便调试
        print(f"Error tracking user behavior: {str(e)}")
        return JsonResponse({
            'status': 'error',
            'message': str(e)
        }, status=400)

class UserBehavior(models.Model):
    # ... 模型定义 ...
    
    @classmethod
    def create_record(cls, user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address):
        return cls.objects.create(
            user_id=user_id,
            session_id=session_id,
            action_type=action_type,
            object_type=object_type,
            object_id=object_id,
            url=url,
            query=query,
            user_agent=user_agent,
            ip_address=ip_address
        )
